package com.wei.czz.framework.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wei.czz.common.enums.CommonEnum;
import com.wei.czz.common.enums.admin.user.UserAppealEnum;
import com.wei.czz.common.dto.admin.UserAppealDto;
import com.wei.czz.common.exception.CzzException;
import com.wei.czz.common.po.UserPo;
import com.wei.czz.common.tool.PageDto;
import com.wei.czz.common.utils.SecurityUtils;
import com.wei.czz.framework.admin.dao.UserAppealDao;
import com.wei.czz.framework.admin.entity.UserAppealEntity;
import com.wei.czz.framework.admin.service.UserAppealService;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * Created by IntelliJ IDEA.
 *
 * @author wei
 * date: 2022-04-15 21:40:54
 * className: UserAppealServiceImpl 用户申诉记录请求服务接口实现类
 * version: 1.0
 * description:
 */
@Service("userAppealService")
@AllArgsConstructor
public class UserAppealServiceImpl extends ServiceImpl<UserAppealDao, UserAppealEntity> implements UserAppealService {

    private static final Logger log = LoggerFactory.getLogger(UserAppealServiceImpl.class);

    @Override
    public void saveOrEdit(UserAppealEntity userAppeal) {
        Long id = userAppeal.getId();
        if (Objects.isNull(id)) {

            int count = baseMapper.insert(userAppeal);
            log.info("插入用户申诉记录完成。count={}", count);
        } else {

            int count = baseMapper.updateById(userAppeal);
            log.info("修改用户申诉记录完成。count={}", count);
        }
    }

    @Override
    public PageDto<UserAppealDto> getPageUserAppealList(Long riskFlowId, Integer pageNum, Integer limit) {

        // 构造mp分页对象
        Page<UserAppealDto> page = new Page<>(pageNum, limit);
        // 查询数据库用户申诉记录表，分页查询用户申诉记录列表
        baseMapper.getUserAppealList(page, riskFlowId);

        for (UserAppealDto userAppealDto : page.getRecords()) {
            if (userAppealDto.getStatus().equals(UserAppealEnum.DO_STATUS.getValue())) {
                // 如果申诉状态是’正在申诉‘，则将审核时间置空
                userAppealDto.setAuditTime(null);
            }
        }
        return new PageDto<>(page);
    }

    @Override
    public UserAppealEntity getLastUserAppeal(Long riskRecordId) {
        LambdaQueryWrapper<UserAppealEntity> userAppealLambdaWrapper = new LambdaQueryWrapper<>();
        // 匹配 风控主键 字段
        userAppealLambdaWrapper.eq(UserAppealEntity::getRiskFlowId, riskRecordId)
                .eq(UserAppealEntity::getDeleteStatus, CommonEnum.ZERO.getLongValue());
        // 根据创建时间排序排序
        userAppealLambdaWrapper.orderByDesc(UserAppealEntity::getCreateTime);
        // 只取第一条数据
        userAppealLambdaWrapper.last("limit 1");
        // 查询数据库用户申诉记录表，获取用户申诉记录信息
        List<UserAppealEntity> userAppealList = this.list(userAppealLambdaWrapper);
        log.info("查询用户申诉记录完成。size={}", userAppealList.size());
        if (userAppealList.isEmpty()) {;
            return null;
        }
        return userAppealList.get(0);
    }

    @Override
    public UserAppealDto getUserAppeal(Long riskRecordId) {
        return baseMapper.getUserAppealDesc(riskRecordId);
    }

    @Override
    public UserAppealEntity findLastOne(Long riskFlowId) {
        LambdaQueryWrapper<UserAppealEntity> userAppealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userAppealLambdaQueryWrapper.eq(UserAppealEntity::getRiskFlowId, riskFlowId)
                .eq(UserAppealEntity::getDeleteStatus, CommonEnum.ZERO.getValue());
        // 查询
        List<UserAppealEntity> userAppealList = baseMapper.selectList(userAppealLambdaQueryWrapper);
        log.info("查询用户申诉记录完成。list.size={}", userAppealList.size());
        return userAppealList.stream().max(Comparator.comparing(UserAppealEntity::getCreateTime))
                .orElse(null);
    }

    @Override
    public void updateUserAppeal(UserAppealEntity userAppeal) {
        if (Objects.isNull(userAppeal.getId())) {
            log.error("用户申诉记录主键为空，修改失败。{}", userAppeal);
            throw new CzzException();
        }
        // 操作数据库用户申诉记录表，更新用户申诉记录数据
        int count = baseMapper.updateById(userAppeal);
        log.info("更新用户申诉记录完成。count={}", count);
    }

    @Override
    public void deleteAppeal(Long riskRecordId) {
        // 获取操作用户
        UserPo userPo = SecurityUtils.getUser();
        Date date = new Date();

        LambdaUpdateWrapper<UserAppealEntity> userAppealLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        userAppealLambdaUpdateWrapper.set(UserAppealEntity::getDeleteStatus, CommonEnum.ONE.getLongValue())
                .set(UserAppealEntity::getUpdateTime, date)
                .set(UserAppealEntity::getUpdateUser, userPo.getUsername())
                .set(UserAppealEntity::getUpdateUserId, userPo.getUserId());
        userAppealLambdaUpdateWrapper.eq(UserAppealEntity::getRiskFlowId, riskRecordId)
                .set(UserAppealEntity::getDeleteStatus, CommonEnum.ZERO.getLongValue());
        // 删除
        int count = baseMapper.update(userAppealLambdaUpdateWrapper);
        log.info("删除用户申诉记录完成。count={}", count);
    }
}